const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const { ModuleFederationPlugin } = require('webpack').container;
const InsertTagPlugin = require('./insert-tag-plugin');
const InsertIconThemePlugin = require('./insert-icon-theme-plugin');
const createLibraryInfo = require('./create-library-info');
const { resolveApp } = require('./resolve');
const moment = require('moment');
const validation = require('./validation');
validation.npmCheck();

const filename = 'remoteEntry.js?v=[chunkhash:8]';
const buildType = process.env.BUILD_TYPE;
const package = require(`${resolveApp('')}/package.json`);

const isProduction = process.env.NODE_ENV === 'production';
const { name, isSpecialApp } = package;
const vendorVersion = '1.0.0',
  buildVersion = moment().format('YYYY-MM-DD-HH-mm-ss');

const { external, libraryPaths } = createLibraryInfo();

const externals = {
  react: 'React',
  'react-dom': 'ReactDOM',
  redux: 'Redux',
  'react-redux': 'ReactRedux',
  'react-router-dom': 'ReactRouterDOM',
  classnames: 'classnames',
  'react-router': 'ReactRouter',
  ...external,
  // '@seeyon/ui': 'SeeyonUI',
  // '@seeyon/ui-mobile': 'SeeyonMUI',
  // "@seeyon/ui-business-attachment": "a1s",
  // "@seeyon/ui-business-basic-data": "as1s",
  // "@seeyon/ui-business-bpm": "ad1s",
  // "@seeyon/ui-business-enums": "af1s",
  // "@seeyon/ui-business-expression": "ag1s",
  // "@seeyon/ui-business-global-frame-layout": "ah1s",
  // "@seeyon/ui-business-icon-library": "aj1s",
  // "@seeyon/ui-business-images-collector": "ak1s",
  // "@seeyon/ui-business-micriservice-selector": "ay1s",
  // "@seeyon/ui-business-online-compiler": "at1s",
  // "@seeyon/ui-business-org-selector": "ar1s",
  // "@seeyon/ui-business-search": "ae1s",
  // "@seeyon/ui-business-serial-scheme": "aw1s",
  // "@seeyon/ui-business-style-designer": "aq1s",
  // "@seeyon/ui-application-category": "aqa1s",
  // "@seeyon/ui-business-where": "az1s",
  // "@seeyon/ui-business-udc-reference": "ax1s",
  // "@seeyon/ui-complex": "ac1s",
  // "@seeyon/ui-dynamic-title": "ab1s",
  // "@seeyon/ui-mobile": "av1s",
  // "@seeyon/ui-business-connector-convert ": "an1s",
  // "@seeyon/ui-router-tabs": "fsfa",

  // "@seeyon/tools": "a106",
  // "react-dnd": "a1113",
  // "react-dnd-html5-backend": "a1113",

  // "pinyin": "awwwa13",
  // "pinyin-pro": "aadafa3",
  // "nodejieba": "aadaafa3",
};

const resolve = {
  modules: ['node_modules', resolveApp('src')],
  extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
  alias: {
    '@': resolveApp('src'),
    '@assets': resolveApp('src/assets'),
    '@components': resolveApp('src/components'),
    '@constants': resolveApp('src/constants'),
    '@containers': resolveApp('src/containers'),
    '@models': resolveApp('src/models'),
    '@pages': resolveApp('src/pages'),
    '@services': resolveApp('src/services'),
    '@root': resolveApp('src'),
    '@redux': resolveApp('src/redux/'),
    '@utils': resolveApp('src/utils'),
    '@locales': resolveApp('src/locales'),
  },
};

const SpecialAppPlug = !isSpecialApp
  ? [
      new InsertIconThemePlugin({
        buildVersion,
      }),
      new InsertTagPlugin({
        js: libraryPaths,
      }),
    ]
  : [
      new InsertTagPlugin({
        js: libraryPaths,
        css: ['/main/static/theme/sy-theme.css'],
      }),
    ];

const plugins = [
  new ModuleFederationPlugin({
    name: name.replace('-'),
    library: { type: 'window', name },
    filename,
    exposes: {
      './Entry': './src/app4Exposes.tsx',
    },
    remotes: {},
    shared: [
      {
        '@seeyon/ui-business-content': {
          singleton: true,
        },
      },
    ],
    // shared: sharedDeps,
  }),
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
  }),
  // new AddAssetHtmlPlugin({
  //   filepath,
  //   hash: isProduction,
  // }),
  ...SpecialAppPlug,
  new HtmlWebpackPlugin({
    template: 'src/index.html',
    favicon: getFavicon(),
    alwaysWriteToDisk: !isProduction,
    chunks: ['index'],
  }),
  new MomentLocalesPlugin(),
];

// 特殊应用不需要ModuleFederationPlugin
if (isSpecialApp) {
  plugins.shift();
}

// 支持自定义graphql地址
const serverConfFile = getServerConf();
if (serverConfFile) {
  plugins.push(
    new AddAssetHtmlPlugin({
      filepath: serverConfFile,
      publicPath: buildType === 'zip' ? './metadata' : `/${name}/metadata`,
      outputPath: '/metadata',
      attributes: { id: name },
    }),
  );
}

function getServerConf() {
  if (fs.existsSync(`${resolveApp('')}/server_conf.js`)) {
    return `${resolveApp('')}/server_conf.js`;
  }
  return null;
}

function getFavicon() {
  if (fs.existsSync(`${resolveApp('src')}/favicon.ico`)) {
    return './src/favicon.ico';
  }
  return null;
}

function getWebpackOverridesConfig() {
  try {
    return fs.existsSync(`${resolveApp('')}/webpack-overrides.js`)
      ? require(`${resolveApp('')}/webpack-overrides.js`)
      : null;
  } catch (error) {
    return null;
  }
}

const clientParams = {
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tEY5NG1ZQUfnvnUbTgS',
  accessKeySecret: 'BwDLoqbrCuag3PyaJJcbykY47LFYGU',
};

module.exports = {
  name,
  isSpecialApp,
  resolve,
  plugins,
  externals,
  isProduction,
  vendorVersion,
  buildVersion,
  getWebpackOverridesConfig,
  clientParams,
};
